<?php

namespace App\Admin\Controllers;

use App\Models\Class_section_group;
use App\Models\Class_type;
use App\Models\Credits_squad;
use App\Models\Squad;
use App\Models\Squad_month;
use App\Models\Student;
use App\Models\Teacher;

use Encore\Admin\Auth\Database\Administrator;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Database\Query\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Credits;
use Encore\Admin\Widgets\Table;
use App\Models\Campus;
use App\Admin\Controllers\Class_sectionController;

class ProblemController extends Controller
{
    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('月度学分');
            $content->description(trans('admin.list'));

            $content->body($this->Problem_Search_form());
            $content->body(view('admin.Problem_squad'));
            //$content->body(view('admin.credits_rules'));
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(trans('admin.teacher'));
            $content->description(trans('admin.edit'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(trans('admin.teacher'));
            $content->description(trans('admin.create'));

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Squad_month::class, function (Grid $grid) {
            $grid->column('时间')->display(function(){
                return $this->year.'年'.$this->season.'学期'.$this->week.'周';
            });
            $grid->squad()->section('班段')->display(function($section){
                return Class_section_group::find($section)->name;
            });
            $grid->squad()->group('分组')->display(function($group){
                return Class_section_group::find($group)->name;
            });
            $grid->squad()->type('班型')->display(function($type){
                return Class_type::find($type)->name;
            });
            $grid->squad()->no('班号');
            $grid->squad()->class_teacher('班主任')->display(function($class_teacher){
                $temp = DB::table('admin_users')->where('id',$class_teacher)->get(['en_name']);
                foreach($temp as $v){
                    return $v->en_name;
                }
            });
            $grid->column('班级人数')->display(function(){
                return DB::table('students')->where('squad_id',$this->squad_id)->count();
            });
            $grid->column('查看')->display(function(){
                return '<a class="fa fa-eye" href="/admin/squad_month/view/'.$this->id.'"></a>';
            });

            //禁用导出按钮
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disableFilter();

            $grid->disableActions();
/*            $grid->filter(function ($filter) {
                $filter->column(1/2, function ($filter) {
                    $filter->disableIdFilter();
                    $filter->like('ch_name',trans('admin.ch_name'));
                });
                $filter->column(1/2, function ($filter) {
                    $filter->disableIdFilter();
                    $filter->like('en_name',trans('admin.en_name'));
                });
            });*/
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Teacher::class, function (Form $form) {
            $form->display('id', 'ID');

            $form->text('ch_name', trans('admin.ch_name'))->rules('required')->addElementLabelClass('must-input');
            $form->text('en_name', trans('admin.en_name'))->rules('required')->addElementLabelClass('must-input');
            $form->select('sex', trans('admin.sex'))->options([1 => trans('admin.men'), 2 => trans('admin.women')]);
            $form->email('email', trans('admin.email'));
            $form->mobile('tel', trans('admin.tel'))->options(['mask' => '999 9999 9999']);
            //去掉添加/编辑表单的重置按钮
            $form->disableReset();
        });
    }

    public function Problem_Search_form()
    {
        //return view('admin.problem_search');
        return Admin::form(Squad::class,function(Form $form){
            $form->setTitle('查看');
            $form->row(function ($row) use ($form)
            {
                $id = Admin::user()->id;
                $row->width(2)->html('<div style="text-align:center"><h3>比较基准</h3></div>');
                $row->width(2)->select('section', trans('admin.section'))->options(function(){
                    return Class_section_group::regulate_options(2);
                })->attribute(['id'=>'section'])->Myload('group', '/api/get_group_user',$id);
                $row->width(2)->select('group',trans('admin.group'))->options(function ($id){
                    return Class_section_group::options($id);
                })->attribute(['id'=>'group']);
                $row->width(2)->select('type','班型')->options(function($id){
                    return Class_type::options($id);
                })->attribute(['id'=>'type']);
                //$row->width(4)->text('start_time','开始时间(包含)')->attribute(['id'=>'startTime']);
                //$row->width(4)->text('end_time','结束时间(包含)')->attribute(['id'=>'endTime']);
                $row->width(2)->date('batch','开班批次')->format('YYYY-MM')->attribute(['id'=>'batch']);
            },  $form);

            $form->row(function ($row) use ($form)
            {
                $id = Admin::user()->id;
                $row->width(2)->html('<div style="text-align:center"><h3>问题项(可多选)</h3></div>');
                $row->width(2)->html('<span class="btn btn-primary" id="kq" style="margin-left: 12px">出勤率低于平均数</span>');
                $row->width(2)->html('<span class="btn btn-primary" id="jx">家校准交低于平均数</span>');
                $row->width(2)->html('<span class="btn btn-primary" id="zy">作业准交低于平均数</span>');
                $row->width(2)->html('<span class="btn btn-primary" id="lost">流失率高于平均数</span>');
            },  $form);

            $form->row(function ($row) use ($form)
            {
                $id = Admin::user()->id;
                $row->width(2)->html('<div style="text-align:center"><h3>时间段</h3></div>');
                $row->width(2)->text('year','年')->default(date('Y'))->attribute(['id'=>'year']);
                $row->width(2)->select('term','学期')->options(function(){
                    $arr[0] = '全部';
                    $arr[1] = '春季学期';
                    $arr[2] = '秋季学期';
                    return $arr;
                })->attribute(['id'=>'week']);
                $row->width(3)->select('start_time','开始时间')->options(function(){
                    $arr = array();
                    for($i=1;$i<25;$i++){
                        $arr[$i] = '第'.$i.'周';
                    }
                    return $arr;
                })->attribute(['id'=>'start_time']);
                $row->width(3)->select('end_time','结束时间')->options(function(){
                    $arr = array();
                    for($i=1;$i<25;$i++){
                        $arr[$i] = '第'.$i.'周';
                    }
                    return $arr;
                })->attribute(['id'=>'end_time']);
            },  $form);

            $form->row(function ($row) use ($form)
            {
                $row->width(5)->html('<div></div>');
                $row->width(3)->html('<div></div><div class="btn btn-danger" id="btn_submit">查询</div><div class="btn btn-info" id="btn_reset">重置</div>');
            },  $form);

            $form->disableReset();
            $form->disableSubmit();
            $form->tools(function (Form\Tools $tools) {
                // 去掉`列表`按钮
                $tools->disableList();
                // 去掉`删除`按钮
                $tools->disableDelete();
                // 去掉`查看`按钮
                $tools->disableView();
            });
        });
    }

    public function problem_submit(Request $request)
    {
        $query = DB::table('squads as s')
            ->join('class_section_groups as cs1','cs1.id','=','s.section')
            ->join('class_section_groups as cs2','cs2.id','=','s.group')
            ->join('admin_users as au','au.id','=','s.class_teacher')
            ->join('class_types as ct','ct.id','=','s.type');

        if(isset($request['section']) && $request['section'] > 0){
            $query = $query->where('s.section',$request['section']);
            if(isset($request['group']) && $request['group'] > 0){
                $query = $query->where('s.group',$request['group']);
            }
        }
        if(isset($request['type']) && $request['type'] > 0){
            $query = $query->where('s.type',$request['type']);
        }
        if(isset($request['batch']) && $request['batch'] != ''){
            $query = $query->where('s.batch',$request['batch']);
        }


        $squads = $query->select('s.id','s.batch','s.no',DB::raw('s.name as squad'),DB::raw('cs1.name as section'),DB::raw('cs2.name as group_name'),DB::raw('au.en_name as tutor'),DB::raw('ct.name as type_name'))->get();
        $squads_id = array();

        foreach($squads as $v){
            $squads_id[$v->id] = $v;
        }

        $query = DB::table('squad_month');
        if(count($squads_id) > 0){
            $query = $query->whereIn('squad_id',array_keys($squads_id));
        }
        if(isset($request['year']) && $request['year'] != ''){
            $query = $query->where('year',$request['year']);
        }
        if(isset($request['term']) && $request['term'] > 0){
            $query = $query->where('season',$request['term']);
        }
        if(isset($request['start_time']) && $request['start_time'] != '' && isset($request['end_time']) && $request['end_time'] != ''){
            $query = $query->where('week','>=',$request['start_time'])->where('week','<=',$request['end_time']);
        }
        $squad_month = $query->get();

        $data = array();$temp = array();
        $total_kq_count = $total_kq_num = 0;
        $total_zy_count = $total_zy_num = 0;
        $total_jx_count = $total_jx_num = 0;
        $total_lost_count = $total_lost_num = 0;
        foreach($squad_month as $v){
            if(!isset($temp[$v->squad_id])){
                $temp[$v->squad_id] = array();
                $temp[$v->squad_id]['kq_count'] = 0;
                $temp[$v->squad_id]['kq_num'] = 0;
                $temp[$v->squad_id]['zy_count'] = 0;
                $temp[$v->squad_id]['zy_num'] = 0;
                $temp[$v->squad_id]['jx_count'] = 0;
                $temp[$v->squad_id]['jx_num'] = 0;
                $temp[$v->squad_id]['lost_count'] = 0;
                $temp[$v->squad_id]['week'] = 9999;
                $temp[$v->squad_id]['stu_num'] = 0;
            }
            if($v->week < $temp[$v->squad_id]['week']){
                $temp[$v->squad_id]['week'] = $v->week;
                $temp[$v->squad_id]['stu_num'] = $v->stu_num;
            }
            if($v->kq_rate > 0){
                $temp[$v->squad_id]['kq_count'] += $v->kq_rate;
                $temp[$v->squad_id]['kq_num'] += 1;
                $total_kq_count += $v->kq_rate;
                $total_kq_num += 1;
            }
            if($v->zy_rate > 0){
                $temp[$v->squad_id]['zy_count'] += $v->zy_rate;
                $temp[$v->squad_id]['zy_num'] += 1;
                $total_zy_count += $v->zy_rate;
                $total_zy_num += 1;
            }
            if($v->jx_rate > 0){
                $temp[$v->squad_id]['jx_count'] += $v->jx_rate;
                $temp[$v->squad_id]['jx_num'] += 1;
                $total_jx_count += $v->jx_rate;
                $total_jx_num += 1;
            }
            $temp[$v->squad_id]['lost_count'] += $v->wastage_num;
            $temp[$v->squad_id]['content'] = $v->content;
        }

        if($total_kq_num == 0){
            $total_kq_num = 1;
        }
        if($total_zy_num == 0){
            $total_zy_num = 1;
        }
        if($total_jx_num == 0){
            $total_jx_num = 1;
        }

        foreach($temp as $k => $v){
            $data[$k]['squad_id'] = $k;
            $data[$k]['content'] = $v['content'];

            if($v['kq_num'] == 0){
                $data[$k]['kq_rate'] = $v['kq_count']/1;
            }else{
                $data[$k]['kq_rate'] = $v['kq_count']/$v['kq_num'];
            }

            if($v['zy_num'] == 0){
                $data[$k]['zy_rate'] = $v['zy_count']/1;
            }else{
                $data[$k]['zy_rate'] = $v['zy_count']/$v['zy_num'];
            }

            if($v['jx_num'] == 0){
                $data[$k]['jx_rate'] = $v['jx_count']/1;
            }else{
                $data[$k]['jx_rate'] = $v['jx_count']/$v['jx_num'];
            }

            $total_lost_count += $v['lost_count'];
            $total_lost_num += $v['stu_num'];
            $data[$k]['wastage_num'] = $v['lost_count'];
            $data[$k]['wastage_rate'] = $v['lost_count']/$v['stu_num'];

            $data[$k]['squad'] = $squads_id[$k]->squad;
            $data[$k]['group_name'] = $squads_id[$k]->group_name;
            $data[$k]['section'] = $squads_id[$k]->section;
            $data[$k]['type_name'] = $squads_id[$k]->type_name;
            $data[$k]['no'] = $squads_id[$k]->no;
            $data[$k]['tutor'] = $squads_id[$k]->tutor;
            $data[$k]['batch'] = $squads_id[$k]->batch;
        }

        /*        $query1 = clone $query;
                $total_data = $query1->select(DB::raw('AVG(kq_rate) as kq'),DB::raw('AVG(zy_rate) as zy'),DB::raw('AVG(jx_rate) as jx'),DB::raw('AVG(wastage_rate) as wastage'),DB::raw('sum(wastage_num) as num'))->get();
                $data = $query->offset(($request['page']-1)*$request['pagesize'])->limit($request['pagesize'])->get();

                foreach($data as $k=>$value){
                    $data[$k] = array_merge((array)$value,(array)$squads_id[$value->squad_id]);
                }*/

        $total_data[0]['kq'] = round($total_kq_count /  $total_kq_num,2);
        $total_data[0]['jx'] = round($total_jx_count /  $total_jx_num,2);
        $total_data[0]['zy'] = round($total_zy_count /  $total_zy_num,2);
        $total_data[0]['wastage'] = round($total_lost_count /  $total_lost_num,2);
        $total_data[0]['num'] = $total_lost_count;


        foreach($data as $k => $v){
            if($request['kq'] && $v['kq_rate'] >= $total_data[0]['kq']){
                unset($data[$k]);
                continue;
            }
            if($request['jx'] && $v['jx_rate'] >= $total_data[0]['jx']){
                unset($data[$k]);
                continue;
            }
            if($request['zy'] && $v['zy_rate'] >= $total_data[0]['zy']){
                unset($data[$k]);
                continue;
            }
            if($request['lost'] && $v['wastage_rate'] <= $total_data[0]['wastage']){
                unset($data[$k]);
                continue;
            }
        }
        $count = count($data);
        $return = array_chunk($data,$request['pagesize']);
        $data = $return[$request['page']-1];


        return array('data'=>$data,'total_data'=>$total_data,'total'=>$count);
    }
}
